<?php
if(!defined('IN_T'))
{
   die('hacking attempt');
}
require_once __DIR__."/../../config/config.php";
require_once __DIR__."/../include/cls_common.php";
class KrOperation{
	private $kr;
	private $cdn_host="http://";
	public function KrOperation(){
		switch ($GLOBALS['_lang']['global_storage']) {
			case 'qiniu':
				require_once __DIR__.'/../qiniu/cls_qiniu2.php';
				$this->kr = new Qiniu();
				$this->cdn_host .= $GLOBALS['_lang']['qiniu_config']['cdn_host'];
				break;
			case 'oss':
				require_once __DIR__.'/../oss/cls_oss2.php';
				$this->kr = new Oss();
				$this->cdn_host .= $GLOBALS['_lang']['oss_config']['cdn_host'];
				break;
		}
		$this->cdn_host.='/';
	}
	public function downloadFile($user_id,$imgs,$origin_dir){
		//创建目录
		$temp_dir = KRTEMP."/".$user_id."/".date('Ymd',Common::gmtime()).Common::get_rand_number()."/";
		Common::make_dir($temp_dir);
		//实例化七牛
		// $qiniu = new qiniu();
		// $cdn_host = $GLOBALS['_lang']['cdn_host'];
		$path="";
		//下载图片
		foreach ($imgs as $img) {
			$obj = $img['imgsrc'];
			$view_uuid=Common::guid(16);
			$file = $this->kr->downloadFile($obj,$temp_dir.$view_uuid.substr($obj,strrpos($obj,".")));

			if($file!=null){
				$info = getimagesize($file);
				if(($info['0']/$info['1']==2)&&( (strpos("image/jpeg",$info['mime'])===0)||(strpos("image/tif", $info['mime'])===0))){
					$filename = $img['imgname'];
					if (strpos($filename, ".jpg")) {
						$filename = substr($filename , 0 , strrpos($filename , "."));
					}
					if (mb_strlen($filename)) {
						$filename = substr($filename, 0,100);
					}
					$path=$path.$file." ";	
					$source = array(
						'filename' =>$filename, 
						'location'  =>$this->cdn_host.$obj,
						'thumb_path'=>$this->cdn_host.$origin_dir.$view_uuid."/thumb.jpg",
						'view_uuid' =>$view_uuid,
						// 'img_size'=>intval(filesize($file)/1024),
						);
					$imgsmain[] = $source;
				}
			}
		}

		$result = array(
			'tempdir'=>$temp_dir,
			'imgsmain'=>$imgsmain,
			'path'=>$path
		);
		return  $result;
	}
	//切图
	public  function slicePano($path){
		exec(KRPANO." ".$path."");
	}
	//上传图片
	public  function uploadFile($dir,$origin_file){
		// $this->kr = new qiniu();
		$this->upload($dir,$origin_file);
	}


	private function upload($dir,$origin_file){
		if(is_dir($dir))
		{
			if ($dh = opendir($dir)) 
			{
				while (($file = readdir($dh)) !== false)
				{
					if((is_dir($dir.$file)) && $file!="." && $file!="..")
					{	
	
						//目录
						$this->upload($dir.$file."/",$origin_file.$file."/");
					}
					else
					{
						if($file!="." && $file!="..")
						{	
							//上传
							$this->kr->uploadFile($dir.$file ,$origin_file.$file);
						}
					}
				}
				closedir($dh);
			}
		}
	}

}

?>